import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';

export default function Login() {
  const [studentId, setStudentId] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const { setUser } = useAuth();

  const handleLogin = async (e) => {
    e.preventDefault();
    setLoading(true);
    if (!studentId || !password) {
      alert('请输入学号和密码');
      setLoading(false);
      return;
    }
    try {
      const res = await fetch('/api/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ student_id: studentId, password })
      });
      const data = await res.json();
      if (data.success) {
        setUser(data.user);
        navigate('/home');
      } else {
        alert(data.message || '学号或密码错误');
      }
    } catch (err) {
      alert('登录失败，请检查网络或稍后再试');
    }
    setLoading(false);
  };

  return (
    <div className="card" style={{ maxWidth: 350 }}>
      <h2 style={{ textAlign: 'center', marginBottom: 24 }}>登录</h2>
      <form onSubmit={handleLogin}>
        <div>
          <input
            type="text"
            placeholder="学号"
            value={studentId}
            onChange={e => setStudentId(e.target.value)}
            style={{ width: '100%', marginBottom: 16 }}
          />
        </div>
        <div>
          <input
            type="password"
            placeholder="密码"
            value={password}
            onChange={e => setPassword(e.target.value)}
            style={{ width: '100%', marginBottom: 16 }}
          />
        </div>
        <button type="submit" style={{ width: '100%', marginBottom: 8 }} disabled={loading}>{loading ? '登录中...' : '登录'}</button>
      </form>
      <div style={{ textAlign: 'right' }}>
        <a href="/register">没有账号？注册</a>
      </div>
    </div>
  );
} 